package com.ll.example.springbootwebdemokotlin.config

import com.alibaba.druid.pool.DruidDataSource
import com.alibaba.druid.support.http.StatViewServlet
import com.alibaba.druid.support.http.WebStatFilter
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.*
import javax.sql.DataSource


/**
 * Druid配置
 */
@Configuration
class DruidConfig {
    //读取druid的配置
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    fun druid(): DataSource {
       val source =DruidDataSource()
//        with(DruidDataSource()) {
//            username = "root"
//            password = "rootroot"
//            driverClassName = "com.mysql.cj.jdbc.Driver"
//            url = "jdbc:mysql://localhost:3306/crudtest?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false"
//
//            initialSize = 5
//            minIdle = 5
//            maxActive = 20
//            maxWait = 60000
//            timeBetweenEvictionRunsMillis = 60000
//            minEvictableIdleTimeMillis = 300000
//            validationQuery = "SELECT 1 FROM DUAL"
//            isTestWhileIdle = true
//            isTestOnBorrow = false
//            isTestOnReturn = false
//            isPoolPreparedStatements = true
//            //        配置监控统计拦截的filters，去掉后监控界面sql无法统计，'wall'用于防火墙
//            setFilters("stat")
//            setFilters("wall")
//            setFilters("slf4j")
//            maxPoolPreparedStatementPerConnectionSize = 20
//            isUseGlobalDataSourceStat = true
//            setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500")
//        }
        return source
    }
    //配置Druid的监控
    //1、配置一个管理后台的servlet
    @Bean
    fun statViewServlet():ServletRegistrationBean<StatViewServlet>{
        //初始化bean并指定处理的路径
        val bean = ServletRegistrationBean(StatViewServlet(), "/druid/*")
        //配置初始化参数
        val initParams = HashMap<String, String>()
        initParams["loginUsername"] = "admin"
        initParams["loginPassword"] = "123456"
          //允许访问的链接，默认允许所有访问
        initParams["allow"] =""
          //拒绝访问的链接,默认不拒绝访问
        initParams["deny"] = "192.168.1.106"
        bean.initParameters=initParams
        return bean

    }
    //2、配置一个web监控的filter
    @Bean
    fun webStatFilter():FilterRegistrationBean<WebStatFilter>{
        val bean=FilterRegistrationBean<WebStatFilter>(WebStatFilter())

        //配置初始化参数
        val initParams = HashMap<String, String>()
        //排除的链接
        initParams["exclusions"]="*.js,*.css,/druid/*"
        bean.initParameters=initParams
        //拦截所有请求
        bean.urlPatterns=Arrays.asList("/*")
        return bean
    }
}